package com.example.service.impl;

import com.example.pojo.Role;
import com.example.pojo.User;
import com.example.service.UserService;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @program: springboot_course
 * @description: 服务实现层
 * @author: ChenZhiXiang
 * @create: 2019-06-10 15:53
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Object saveUser() {
        List<Role> list = new LinkedList<>();
        User user = new User();
        Role role1 = new Role(2,"无双剑姬","我是一个用剑的艺术家（画了个提莫）没有骗你吧~");
        Role role2 = new Role(3,"疾风剑豪","死亡如风,常伴吾身");
        Role role3 = new Role(4,"放逐之刃","刀剑映出了战士的心。而我的心，漆黑且残破");
        list.add(role1);
        list.add(role2);
        list.add(role3);
        user.setId(2L);
        user.setUserName("酒后少女的梦");
//        user.setNote("一个英雄联盟资深玩家");
        user.setRoles(list);
        return mongoTemplate.insert(user);
    }

    @Override
    public DeleteResult deleteUser(Long id) {
        // 构造id相等的条件
        Criteria criteria = Criteria.where("id").is(id);
        // 查询对象
        Query query = Query.query(criteria);
        // 删除用户
        DeleteResult deleteResult = mongoTemplate.remove(query,User.class);
        return deleteResult;
    }

    @Override
    public List<User> findUser(String userName, String note, int skip, int limit) {
        // 将用户名和备注设置为模糊查询准则
        Criteria criteria = Criteria.where("userName").regex(userName).and("note").regex(note);
        // 构建查询条件，并设置分页跳过前skip个，至多返回limit个
        /*Query query = Query.query(criteria).limit(limit).skip(skip);*/
        Query query = Query.query(criteria);
        // 执行
        List<User> list = mongoTemplate.find(query,User.class);
        return list;
    }

    @Override
    public UpdateResult updateUser(Long id, String userName, String note) {
        // 构造id相等的条件
        Criteria criteria = Criteria.where("id").is(id);
        Query query = Query.query(criteria);
        // 定义更新的对象，后续可变化的字符串代表排除在外的属性
        Update update = Update.update("userName",userName);
        update.set("note",note);
        // 更新第一个文档
        UpdateResult result = mongoTemplate.updateFirst(query,update,User.class);
        return result;
    }

    @Override
    public User getUser(Long id) {
        return mongoTemplate.findById(id,User.class);
    }
}
